package authorize_controller

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"shimmer/neusoft_club_backend/dao/domain"
	"shimmer/neusoft_club_backend/middlewares/auth_middleware"
	"shimmer/neusoft_club_backend/services"
	"shimmer/neusoft_club_backend/services/assets_service"
)

type accountPasswordAuthorizerReq struct {
	Account  string `json:"account" form:"account" xml:"account" binding:"required"`
	Password string `json:"password" form:"password" xml:"password" binding:"required"`
}

// @Summary 用户账号密码登录
// @Description 登录
// @Tags 鉴权
// @accept json
// @Produce json
// @Param account body authorize_controller.accountPasswordAuthorizerReq true "account"
// @Success 200 {object} domain.UserDTO
// @Router /api/authorize/self/ap [post]
func accountPasswordAuthentication(c *gin.Context) {
	authorizer := accountPasswordAuthorizerReq{}
	err := c.ShouldBind(&authorizer)
	session := sessions.Default(c)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	authorizer.Password, err = domain.HashPassword(authorizer.Password)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	account := domain.Account{}

	err = services.DBEngine.Model(&account).Where("account = ? and password = ? ", &authorizer.Account, &authorizer.Password).Joins("User").Find(&account).Error

	if err != nil {
		services.AbortWithError(c, err)
		return
	}

	user := account.User

	if user == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"error": "not found user in authorizer",
		})
		return
	}
	session.Set(domain.UserSessionID, user.ID)
	err = session.Save()
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	c.JSON(http.StatusOK, user)
}

// @Summary 用户注销
// @Description 注销
// @Tags 鉴权
// @Success 204
// @Router /api/authorize/self [delete]
func logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete(domain.UserSessionID)
	err := session.Save()
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	c.JSON(200, gin.H{
		"success": true,
	})
}

// @Summary 获取用户信息
// @Description 获取用户信息
// @Tags 鉴权,用户
// @Success 200 {object} domain.UserDTO
// @Router /api/authorize/self [get]
func getSelfInfo(c *gin.Context) {
	user, err := domain.GetUserFromContext(c)
	if err != nil {
		services.AbortWithError(c, err)
		c.Abort()
	}
	if user == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"error": "not found user in context",
		})
		return
	}
	user.Avatar, err = assets_service.FindAssetById(*user.AvatarID)
	if err != nil {
		services.AbortWithError(c, err)
	}
	c.JSON(http.StatusOK, user)
}

func ConfigAuthorizationController(groupConfig *gin.RouterGroup) {
	groupConfig.POST("/self/ap", accountPasswordAuthentication)
	groupConfig.GET("/self", auth_middleware.AuthLoginMiddleware(), getSelfInfo)
	groupConfig.DELETE("/self", logout)
}
